package com.fastadmin.mapper.impl;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fastadmin.config.quartz.QuartzJob;
import com.fastadmin.pojo.FastParam;
import com.xphsc.easyjdbc.EasyJdbcTemplate;
import com.xphsc.easyjdbc.page.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

@Repository
@Slf4j
public class QuartzJobMapper extends BaseMapper {
    @Autowired
    EasyJdbcTemplate easyJdbcTemplate;

    Table table = AnnotationUtil.getAnnotation(QuartzJob.class, Table.class);

    public PageInfo<QuartzJob> findByFastParam(FastParam fastParam) {

        PageInfo<QuartzJob> pageInfo = this.easyJdbcTemplate.findByPage(fastParam.getSql(table.name()), QuartzJob.class, fastParam.getOffset(), fastParam.getLimit());
        return pageInfo;
    }

    public QuartzJob findById(String ids) {
        QuartzJob quartzjob = this.easyJdbcTemplate.getByPrimaryKey(QuartzJob.class, ids);
        return quartzjob;
    }

    public void deleteById(String id) {
        this.easyJdbcTemplate.deleteByPrimaryKey(QuartzJob.class, id);
    }

    public void update(QuartzJob quartzjob) {
        quartzjob.setUpdate_time(new Timestamp(System.currentTimeMillis()));
        this.easyJdbcTemplate.update(quartzjob);
    }

    public Object save(QuartzJob quartzjob) {
        quartzjob.setCreate_time(new Timestamp(System.currentTimeMillis()));
        quartzjob.setUpdate_time(new Timestamp(System.currentTimeMillis()));
        return this.easyJdbcTemplate.insertKey(quartzjob);

    }

    public List<QuartzJob> findByIds(String ids) {
        if (StrUtil.isBlank(ids)) {
            return CollUtil.newArrayList();
        }
        return this.easyJdbcTemplate.findByIds(QuartzJob.class, Arrays.asList(StrUtil.splitToArray(ids, ',')));

    }


    /**
     * 查找所有未暂停的job
     * @return
     */
    public List<QuartzJob> findAllNotPause() {
        String sql = "SELECT * FROM " + table.name() + " WHERE 1=1 AND is_pause =true";
        List<QuartzJob> quartzJobs = easyJdbcTemplate.find(sql, QuartzJob.class);
        return quartzJobs;
    }
}
